package com.wanmait.myhouse.mediatorController;

import com.wanmait.myhouse.dao.MediatorDAO;
import com.wanmait.myhouse.vo.Mediator;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("mediator")
public class MediatorBcColorController {
    @PostMapping("updateInfo")
    public String updateInfo(Mediator mediator, MultipartFile face, HttpServletRequest request,HttpSession session){
        if (!face.isEmpty()){
            String filepath = request.getServletContext().getRealPath("/static/mediator/images");
            String originalName = face.getOriginalFilename();
            String fileext = FilenameUtils.getExtension(originalName);
            String filename = UUID.randomUUID().toString()+"."+fileext;
            try {
                face.transferTo(new File(filepath+"/"+filename));
            } catch (IOException e) {
                e.printStackTrace();
            }
            mediator.setHeadImg(filename);
        }
        Object o = session.getAttribute("mediator");
        Mediator m = (Mediator)o;
        mediator.setMediatorRegtime(m.getMediatorRegtime());
        MediatorDAO mediatorDAO = new MediatorDAO();
        mediatorDAO.addAll(mediator);
        session.invalidate();

        return "redirect:/mediator/bcColor";
    }

    @GetMapping("bcColor")
    public String bcColor(){
        return "/mediator/bc_color";
    }
}
